﻿using Admin.Application.Const;
using Admin.Application.DynamicApi.System.Dict.Dto;
using Admin.Database.Enums;
using Admin.Database.Model;
using Framework.Core;
using Framework.Core.CustomException;
using Framework.DI;
using Framework.DynamicApiController;
using Framework.SqlSugar;
using Framework.SqlSugar.Repository;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Admin.Application.DynamicApi.System.Dict
{
	/// <summary>
	/// 系统字典类型服务 🧩
	/// </summary>
	[Service]
	public class SysDictTypeService : ISelfTransientAutoInject
	{
		private readonly SqlSugarRepository<SysDictType> _sysDictTypeRep;
		private readonly SysDictDataService _sysDictDataService;
		private readonly CacheHelp _sysCacheService;
		private readonly UserManager _userManager;

		public SysDictTypeService(SqlSugarRepository<SysDictType> sysDictTypeRep,
			SysDictDataService sysDictDataService,
			CacheHelp sysCacheService,
			UserManager userManager)
		{
			_sysDictTypeRep = sysDictTypeRep;
			_sysDictDataService = sysDictDataService;
			_sysCacheService = sysCacheService;
			_userManager = userManager;
		}

		/// <summary>
		/// 获取字典类型分页列表 🔖
		/// </summary>
		/// <returns></returns>
		[DisplayName("获取字典类型分页列表")]
		public async Task<SqlSugarPagedList<SysDictType>> Page(PageDictTypeInput input)
		{
			return await _sysDictTypeRep.AsQueryable()
				.WhereIF(!string.IsNullOrEmpty(input.Code?.Trim()), u => u.Code.Contains(input.Code))
				.WhereIF(!string.IsNullOrEmpty(input.Name?.Trim()), u => u.Name.Contains(input.Name))
				.OrderBy(u => new { u.OrderNo, u.Code })
				.ToPagedListAsync(input.Page, input.PageSize);
		}

		/// <summary>
		/// 获取字典类型列表 🔖
		/// </summary>
		/// <returns></returns>
		[DisplayName("获取字典类型列表")]
		public async Task<List<SysDictType>> GetList()
		{
			return await _sysDictTypeRep.AsQueryable().OrderBy(u => new { u.OrderNo, u.Code }).ToListAsync();
		}

		/// <summary>
		/// 获取字典类型-值列表 🔖
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[DisplayName("获取字典类型-值列表")]
		public async Task<List<SysDictData>> GetDataList([FromQuery] GetDataDictTypeInput input)
		{
			var dictType = await _sysDictTypeRep.GetFirstAsync(u => u.Code == input.Code) ?? throw new CustomException("字典值不存在");
			return await _sysDictDataService.GetDictDataListByDictTypeId(dictType.Id);
		}

		/// <summary>
		/// 添加字典类型 🔖
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[HttpPost]
		[DisplayName("添加字典类型")]
		public async Task AddDictType(AddDictTypeInput input)
		{
			if (input.Code.ToLower().EndsWith("enum")) throw new CustomException("字典编码不能以Enum结尾");

			var isExist = await _sysDictTypeRep.IsAnyAsync(u => u.Code == input.Code);
			if (isExist) throw new CustomException("字典类型已存在,名称或编码重复");

			await _sysDictTypeRep.InsertAsync(input.Adapt<SysDictType>());
		}

		/// <summary>
		/// 更新字典类型 🔖
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[UnitOfWork]
		[HttpPost]
		[DisplayName("更新字典类型")]
		public async Task UpdateDictType(UpdateDictTypeInput input)
		{
			var dict = await _sysDictTypeRep.GetFirstAsync(x => x.Id == input.Id);
			if (dict == null) throw new CustomException("字典值不存在");

			if (dict.Code.ToLower().EndsWith("enum") && input.Code != dict.Code) throw new CustomException("禁止修改枚举类型的字典编码");

			var isExist = await _sysDictTypeRep.IsAnyAsync(u => u.Code == input.Code && u.Id != input.Id);
			if (isExist) throw new CustomException("字典类型已存在,名称或编码重复");

			_sysCacheService.Remove($"{CacheConst.KeyDict}{input.Code}");
			await _sysDictTypeRep.UpdateAsync(input.Adapt<SysDictType>());
		}

		/// <summary>
		/// 删除字典类型 🔖
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[UnitOfWork]
		[HttpPost]
		[DisplayName("删除字典类型")]
		public async Task DeleteDictType(DeleteDictTypeInput input)
		{
			var dictType = await _sysDictTypeRep.GetByIdAsync(input.Id) ?? throw new CustomException("字典值不存在");

			// 删除字典值
			await _sysDictTypeRep.DeleteAsync(dictType);
			await _sysDictDataService.DeleteDictData(input.Id);
		}

		/// <summary>
		/// 获取字典类型详情 🔖
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[DisplayName("获取字典类型详情")]
		public async Task<SysDictType> GetDetail([FromQuery] DictTypeInput input)
		{
			return await _sysDictTypeRep.GetByIdAsync(input.Id);
		}

		/// <summary>
		/// 修改字典类型状态 🔖
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[UnitOfWork]
		[DisplayName("修改字典类型状态")]
		public async Task SetStatus(DictTypeInput input)
		{
			var dictType = await _sysDictTypeRep.GetByIdAsync(input.Id) ?? throw new CustomException("字典值不存在");

			_sysCacheService.Remove($"{CacheConst.KeyDict}{dictType.Code}");

			dictType.Status = input.Status;
			await _sysDictTypeRep.AsUpdateable(dictType).UpdateColumns(u => new { u.Status }, true).ExecuteCommandAsync();
		}

		/// <summary>
		/// 获取所有字典集合 🔖
		/// </summary>
		/// <returns></returns>
		[DisplayName("获取所有字典集合")]
		public async Task<dynamic> GetAllDictList()
		{
			var ds = await _sysDictTypeRep.AsQueryable()
				.InnerJoin(_sysDictDataService.VSysDictData, (u, w) => u.Id == w.DictTypeId)
				.Select((u, w) => new
				{
					TypeCode = u.Code,
					w.Label,
					w.Value,
					w.Code,
					w.TagType,
					w.StyleSetting,
					w.ClassSetting,
					w.ExtData,
					w.Remark,
					w.OrderNo,
					Status = w.Status == StatusEnum.Enable && u.Status == StatusEnum.Enable ? StatusEnum.Enable : StatusEnum.Disable
				})
				.ToListAsync();
			return ds.OrderBy(u => u.OrderNo).GroupBy(u => u.TypeCode).ToDictionary(u => u.Key, u => u);
		}
	}
}
